package coreSimulation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Iterator;

import queue.Queue;
import utils.Logger;
import dropoffdesk.DropOffDesk;

/**
 * Handles window close events from the GUI. This class closes open queues and
 * drop-off desks, logs and removes any remaining passengers in the queue then
 * closes the application
 * 
 * @author Andrew Stokes
 * 
 */
public class WindowController implements WindowListener {

	private DropOffDesk desk;
	private Queue queue;

	public WindowController(DropOffDesk desk, Queue queue) {
		this.desk = desk;
		this.queue = queue;

	}

	// handle the window close event
	@Override
	public void windowClosing(WindowEvent arg0) {

		Thread thread = new Thread(
		/*
		 * anonymous runnable class to clear the queue of remaining passengers
		 * and close the program. This is done asynchronously in order to allow
		 * the UI to stay responsive and displaying the changes
		 */

		new Runnable() {
			@Override
			public void run() {
				{
					// close the drop-off desk
					synchronized (desk) {
						desk.setIsOpen(false);
					}
					// close the queue and remove any remaining
					// passengers
					synchronized (queue) {

						queue.setIsOpen(false);
						if (!queue.getIsEmpty()) {

							queue.setStatus("Queue closed - logging remaining passengers");
							try {
								Thread.sleep(2000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							for (Iterator<Passenger> it = queue.iterator(); it
									.hasNext();) {
								// log the fact that the remaining
								// passengers in
								// the queue were unable to board
								// and were checked off the flight
								Logger.getLogger()
										.appendLog(
												Logger.EVENT,
												queue.removeFirst().toString()
														+ " removed from queue after desk closure and checked off flight.");
								try {
									Thread.sleep(500);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}

							}

						}

						System.exit(0);
					}
				}

			}
		});
		thread.start();

	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		// method not implemented
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// method not implemented
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// method not implemented
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// method not implemented
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
		// method not implemented
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
		// method not implemented
	}

}
